package org.example.service.impl;

import org.example.mapper.CategoryMapper;
import org.example.mapper.GoodsMapper;
import org.example.pojo.Category;
import org.example.pojo.Goods;
import org.example.pojo.Result;
import org.example.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private GoodsMapper goodsMapper;

    /**
     * 查询所有分类
     * @return
     */
    @Override
    public List<Category> list() {
        return categoryMapper.getCategorylist();
    }

    /**
     * 添加分类
     * @param category
     */
    @Override
    public void add(Category category) {
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.add(category);
    }

    /**
     * 修改分类
     * @param category
     */
    @Override
    public void update(Category category) {
        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.update(category);
    }

    /**
     * 删除分类
     * @param id
     */
    @Override
    public void delete(Integer id) {
        // 查询该分类是否关联了商品，如果关联了，则抛出业务异常
        List<Goods> goodsList = goodsMapper.listByCategoryId(id);
        if (goodsList != null && !goodsList.isEmpty()) {
            throw new RuntimeException("该分类关联了商品，不能删除");
        }
        // 删除分类
        categoryMapper.delete(id);
    }
}
